﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	FieldSet.cs
//  Developer:	Solomatov Igor
//  Created:	03.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Smart.Common.WebControls
{
	/// <summary>
	/// Html FieldSet
	/// </summary>
	[ToolboxData("<{0}:FieldSet Text=\"Group\" runat=\"server\"></{0}:FieldSet>")]
	public class FieldSet : WebControl
	{
		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		[Localizable(true)]
		public string Text
		{
			get { return (string) ViewState["Text"] ?? string.Empty; }
			set { ViewState["Text"] = value; }
		}

		/// <summary>
		/// Html FieldSet
		/// </summary>
		public FieldSet()
			: base(HtmlTextWriterTag.Fieldset)
		{
		}

		[NonSerialized] protected HtmlGenericControl Legend;

		protected override void CreateChildControls()
		{
			AddLegend();

			base.CreateChildControls();
		}

		/// <summary>
		/// Add legend control
		/// </summary>
		public virtual void AddLegend()
		{
			if (Legend != null)
				return;

			var lid = "l" + ID;

			Legend = new HtmlGenericControl("legend") {ID = lid, InnerText = Text};

			if (Controls.Count > 0)
				Controls.AddAt(0, Legend);
			else
				Controls.Add(Legend);
		}

		/// <summary>
		/// Add child control to group
		/// </summary>
		public virtual void AddControl(Control ctrl)
		{
			if (DesignMode)
				return;

			if (Legend == null)
				EnsureChildControls();

			Controls.Add(ctrl);
		}
	}
}